package com.game.doudizhu.service;

import com.game.doudizhu.model.GameRoom;
import com.game.doudizhu.model.Player;
import com.game.doudizhu.model.ShopItem;
import com.game.doudizhu.model.SystemSettings;
import com.game.doudizhu.repository.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class AdminService {

    private final PlayerRepository playerRepository;
    private final GameRoomRepository gameRoomRepository;
    private final ShopItemRepository shopItemRepository;
    private final GameService gameService;
    private final PlayerService playerService;
    private final GameRoomService gameRoomService;
    private final SystemSettingsRepository systemSettingsRepository;
    private final FriendshipRepository friendshipRepository;
    private final PlayerItemRepository playerItemRepository;

    public Map<String, Object> getDashboardData() {
        Map<String, Object> data = new HashMap<>();
        data.put("onlineUsers", playerService.getOnlinePlayersCount());
        data.put("activeRooms", gameRoomRepository.countByStatus("PLAYING"));
        data.put("todayRegisters", playerRepository.countByRegisterTimeAfter(LocalDateTime.now().withHour(0)));
        data.put("systemIncome", calculateSystemIncome());
        return data;
    }

    private int calculateSystemIncome() {
        // 实现计算系统收入的逻辑
        return 0; // 临时返回
    }

    public List<Player> getAllUsers() {
        return playerRepository.findAll();
    }

    @Transactional
    public void toggleUserBan(Long userId) {
        Player player = playerRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 如果用户在游戏中，先将其从游戏中移除
        GameRoom currentRoom = gameRoomService.findRoomByPlayerId(userId);
        if (currentRoom != null) {
            gameRoomService.handlePlayerLeave(currentRoom.getId(), userId);
        }
        
        // 更新用户状态，处理 status 为 null 的情况
        String currentStatus = player.getStatus();
        if (currentStatus == null) {
            currentStatus = "ACTIVE"; // 设置默认状态
        }
        
        String newStatus = currentStatus.equals("ACTIVE") ? "BANNED" : "ACTIVE";
        player.setStatus(newStatus);
        playerRepository.save(player);
    }

    @Transactional
    public void deleteUser(Long userId) {
        Player player = playerRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 检查用户是否在游戏中
        GameRoom currentRoom = gameRoomService.findRoomByPlayerId(userId);
        if (currentRoom != null) {
            throw new RuntimeException("用户当前在游戏中，无法删除");
        }
        try {
            // 删除好友关系
            friendshipRepository.deleteByPlayerIdOrFriendId(userId, userId);

            // 删除用户拥有的物品
            playerItemRepository.deleteByPlayerId(userId);

            // 最后删除用户
            playerRepository.delete(player);
        } catch (Exception e) {
            throw new RuntimeException("删除用户失败：" + e.getMessage());
        }

    }

    public List<GameRoom> getAllRooms() {
        return gameRoomRepository.findAll();
    }

    @Transactional
    public void closeRoom(Long roomId) {
        GameRoom room = gameRoomRepository.findById(roomId)
            .orElseThrow(() -> new RuntimeException("房间不存在"));
        gameRoomService.closeRoom(room);
    }

    public List<ShopItem> getAllShopItems() {
        return shopItemRepository.findAll();
    }


    public ShopItem getShopItem(Long itemId) {
        return shopItemRepository.findById(itemId)
                .orElseThrow(() -> new RuntimeException("商品不存在"));
    }
    @Transactional
    public ShopItem createShopItem(ShopItem item) {
        return shopItemRepository.save(item);
    }

    @Transactional
    public ShopItem updateShopItem(Long itemId, ShopItem item) {
        if (!shopItemRepository.existsById(itemId)) {
            throw new RuntimeException("商品不存在");
        }
        item.setId(itemId);
        return shopItemRepository.save(item);
    }

    @Transactional
    public void deleteShopItem(Long itemId) {
        shopItemRepository.deleteById(itemId);
    }

    public Map<String, Object> getSystemSettings() {
        Map<String, Object> settings = new HashMap<>();
        List<SystemSettings> systemSettings = systemSettingsRepository.findAll();
        
        // 设置默认值
        settings.put("initialScore", "1000");
        settings.put("baseScore", "100");
        settings.put("playTimeout", "30");
        settings.put("readyTimeout", "20");
        
        // 用数据库中的值覆盖默认值
        systemSettings.forEach(setting -> 
            settings.put(setting.getKey(), setting.getValue())
        );
        
        return settings;
    }

    @Transactional
    public void updateSystemSettings(Map<String, Object> settings) {
        settings.forEach((key, value) -> {
            SystemSettings setting = systemSettingsRepository.findById(key)
                .orElse(new SystemSettings());
            setting.setKey(key);
            setting.setValue(String.valueOf(value));
            systemSettingsRepository.save(setting);
        });
    }

    public List<Player> searchUsers(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return playerRepository.findAll();
        }
        return playerRepository.findByUsernameLike("%" + keyword + "%");
    }

    public Map<String, Object> getUserStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取用户状态统计
        List<Object[]> statusStats = playerRepository.countByStatusGroup();
        Map<String, Long> statusCounts = new HashMap<>();
        statusStats.forEach(stat -> 
            statusCounts.put((String)stat[0], (Long)stat[1])
        );
        stats.put("statusStats", statusCounts);
        
        // 获取今日注册用户数
        LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        long todayRegisters = playerRepository.countByRegisterTimeAfter(todayStart);
        stats.put("todayRegisters", todayRegisters);
        
        // 获取总用户数
        long totalUsers = playerRepository.count();
        stats.put("totalUsers", totalUsers);
        
        return stats;
    }

    public void resetUserPassword(Long userId, String newPassword) {
        Player player = playerRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
        // TODO: 密码加密
        player.setPassword(newPassword);
        playerRepository.save(player);
    }

    public void updateUserScore(Long userId, Integer scoreChange) {
        Player player = playerRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
        player.setScore(player.getScore() + scoreChange);
        playerRepository.save(player);
    }
} 